{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %}
{% import "bootstrap/fixes.html" as fixes %}
{% import "bootstrap/utils.html" as util %}

{% block title %}Pathway Overlap Comparison{% endblock %}

{% block styles %}
    {{ super() }}
    <link rel="stylesheet" type="text/css" href='https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css'/>

    <style>

        /* Gene Sets in table info */

        td {
            overflow: scroll;
        }

        /* VennDiagram CSS */

        svg path {
            stroke: white;
            stroke-width: 2px;
        }

        #venn-diagram svg text {
            fill: white;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            font-size: 14px !important;
        }

        .venntooltip {
            position: absolute;
            text-align: center;
            width: 128px;
            height: 25px;
            background: #333;
            color: #ddd;
            padding: 2px;
            border: 0px;
            border-radius: 8px;
            opacity: 0;
        }


    </style>
{% endblock %}

{% block scripts %}
    {{ super() }}
    {% include "dependencies/common.html" %}
    {% include "dependencies/venn.html" %}

    <script>
        var data = {{ venn_diagram_data|tojson|safe }};

        // Adjust the height depending on the size of the Euler diagram
        var numberOfIntersections = data.length;

        var height;

        if (numberOfIntersections < 10) {
            height = 400;
        }
        else if (10 <= numberOfIntersections && numberOfIntersections < 30) {
            height = 600;
        }
        else {
            height = 800;
        }

        if (numberOfIntersections > 1000) {
            alert('You have selected a large amount of pathways, the visualization needs some time to be cooked :)')
        }

        var vennDiv = d3.select("#venn-diagram");

        vennDiv.attr("align", "center"); // Align center the diagram

        var diagram = venn.VennDiagram()
            .width($('.panel-body').width() - 100) // Default width of the panel
            .height(height); // Plot the Venn Diagram
        vennDiv.datum(data).call(diagram); // Stick data

        // add a tooltip
        var tooltip = d3.select("body").append("div")
            .attr("class", "venntooltip");

        // add listeners to all the groups to display tooltip on mouseover
        vennDiv.selectAll("g")
            .on("mouseover", function (d, i) {
                // sort all the areas relative to the current item
                venn.sortAreas(vennDiv, d);

                // Display a tooltip with the current size
                tooltip.transition().duration(400).style("opacity", .9);
                tooltip.text(d.size + " genes");

                // highlight the current path
                var selection = d3.select(this).transition("tooltip").duration(400);
                selection.select("path")
                    .style("stroke-width", 3)
                    .style("fill-opacity", d.sets.length == 1 ? .4 : .1)
                    .style("stroke-opacity", 1);
            })

            .on("mousemove", function () {
                tooltip.style("left", (d3.event.pageX) + "px")
                    .style("top", (d3.event.pageY - 28) + "px");
            })

            .on("mouseout", function (d, i) {
                tooltip.transition().duration(400).style("opacity", 0);
                var selection = d3.select(this).transition("tooltip").duration(400);
                selection.select("path")
                    .style("stroke-width", 0)
                    .style("fill-opacity", d.sets.length == 1 ? .25 : .0)
                    .style("stroke-opacity", 0);
            });


        // Info box controller
        /**
         * Creates a new row in Node/Edge info table
         * @param {object} table: table object
         * @param {int} row: row number
         * @param {string} column1: string for column1
         * @param {string} column2: string for column2
         */
        function insertRow(table, row, column1, column2) {

            var row = table.insertRow(row);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = column1;
            cell2.innerHTML = column2;
        }

        /**
         * Renders node info table
         * @param {object} data object
         */
        function populateInfoTable(data) {

            var dynamicTable = document.getElementById('info-table');

            while (dynamicTable.rows.length > 0) {
                dynamicTable.deleteRow(0);
            }
            delete data.sets;

            var tableObject = {};

            if ("intersection" in data) {
                tableObject["Pathway(s)"] = data["intersection"];
            }
            else {
                tableObject["Pathway(s)"] = data["label"];
            }

            tableObject["Gene Set Size"] = data["size"];

            tableObject["Gene Set"] = data["gene_set"].join(", ") + ' <a id="export-link" href="#"><span onclick="exportGenes();" class=\"glyphicon glyphicon-new-window\"></span></a>';

            window.gene_set = data["gene_set"];

            var row = 0;
            $.each(tableObject, function (key, value) {
                insertRow(dynamicTable, row, key, value);
                row++
            });
        }

        // Add table creation
        vennDiv.selectAll("g").on("dblclick", function (d, i) {
            populateInfoTable(d);
        });

        function exportGenes() {
            var anchor = document.querySelector('#export-link');

            anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(window.gene_set.join("\n"));
            anchor.download = 'gene_set.txt';

        }


    </script>

{% endblock %}

{% block content %}
    <div class="container" style="margin-top: 50px">
        {{ util.flashed_messages(dismissible=True, container=False) }}

        <div class="panel panel-default">
            <div class="panel-heading">Visualize Gene Set Overlap across Pathways</div>
            <div class="panel-body">
                <p class="pull-right">Click to see information about overlaps</p>
                <div id="venn-diagram">
                </div>
            </div>
            <table id="info-table" class="table table-bordered table-hover table-responsive"></table>
        </div>
    </div>
    {% include "meta/footer.html" %}
{% endblock %}
